package org.pms.demo.webservice.sign;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.util.SimpleByteSource;
import org.pms.demo.webservice.content.PmsContent;
import org.pms.demo.webservice.dao.RedisUtil;

import javax.annotation.Resource;

/**
 * Created by xusaike on 17/6/9.
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        Object accountCredentials = getCredentials(info);
       // Object user_name = info.getPrincipals().
        String pwdType = String.valueOf(token.getPassword());// 判断一下密码是否是用户输入的，还是JCIS传过来的
        //密码不能大于32位
        if(pwdType.length()>31){
            pwdType = pwdType.substring(0,32);
        }
        //密码长度=32位，说明是md5加密过，是从xx传进来的 32位加密。
        if (pwdType.length() == 32) {
            return equals(pwdType, accountCredentials);
        }



        String username = (String) token.getPrincipal();

        String redis_key = PmsContent.REDIS_RETRY_COUNT+username;
        // retry count + 1
        Object ob = redisUtil.get(redis_key);
        int retryCount = 0;
        if(ob!=null){
            retryCount = (int)ob;
        }


        if (retryCount > PmsContent.RETRY_LOGIN_COUNT) {
            // if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }else{
            redisUtil.set(redis_key,++retryCount,PmsContent.REDIS_AN_HOUR);
        }



        Object salt = null;
        //不考虑向后兼容
        if (info instanceof SaltedAuthenticationInfo) {
            salt = ((SaltedAuthenticationInfo) info).getCredentialsSalt();
        }
        String user_salt = "";
        if(salt!=null){
            user_salt = new String(((SimpleByteSource)salt).getBytes());
        }

        String pwdUser = MD5.getMd5(String.valueOf(token.getPassword()),user_salt);//不等于32 是用户输入的密码。 如果用户输入的密码长度位32那么里面会有一个bug
        boolean matches = equals(pwdUser, accountCredentials);

        if (matches) {
            // clear retry count
            redisUtil.remove(redis_key);
        }


        return matches;
        //将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
       // return super.doCredentialsMatch(token, info) ;
    }

}